package editors.gui;
import graphics.system.Color;
import graphics.system.GLTools;
import tools.Help;
import tools.Point;
public class GuiText extends GuiObject {
	private boolean editmode;
	private String text;
	private int cursor;
	public GuiText(Point pos, float width) {
		super();
		this.rect = new Rect(pos.add(new Point(width / 2, -GuiSettings.LINEHEIGHT / 2)), width, GuiSettings.LINEHEIGHT);
		editmode = false;
		this.text = "";
		cursor = 0;
	}
	@Override
	public boolean isClicked() {
		return clicked;
	}
	@Override
	public boolean checkClick(Point mp) {
		clicked = rect.isIn(mp);
		if (clicked && !editmode)
			editmode = true;
		return clicked;
	}
	public void addChar(char c) {
		if (!editmode)
			return;
		if (cursor > 0 && cursor < text.length()) {
			text = text.substring(0, cursor) + c + text.substring(cursor);
			cursor++;
		}
		else {
			if (cursor == 0) {
				text = c + text;
				cursor++;
			}
			else if (cursor == text.length()) {
				text = text + c;
				cursor++;
			}
		}
	}
	public void moveCursor(int d) {
		if (!editmode)
			return;
		cursor += d;
		if (cursor < 0)
			cursor = 0;
		if (cursor > text.length())
			cursor = text.length();
	}
	public void deleteChar() {
		if (!editmode)
			return;
		if (cursor > 0 && cursor < text.length()) {
			text = text.substring(0, cursor - 1) + text.substring(cursor);
			cursor--;
		}
		else {
			if (cursor == text.length() && cursor != 0) {
				text = text.substring(0, text.length() - 1);
				cursor--;
			}
		}
	}
	public String getText() {
		return this.text;
	}
	@Override
	public void draw() {
		rect.draw(GuiSettings.TEXT_EDIT_BG);
		Point s = rect.getTopLeft();
		s.sAdd(new Point(2, -GuiSettings.FONTADJUST));
		GLTools.drawText(s, text, GuiSettings.TEXT_COL, GuiSettings.FONTSIZE);
		if (editmode)
			GLTools.drawRect(s.add(new Point(cursor * 10 * GuiSettings.FONTSIZE, 5)), 1, GuiSettings.LINEHEIGHT * 0.8f, 0, Color.white);
	}
	public void stopEdit() {
		this.editmode = false;
	}
	public boolean isEditing() {
		return editmode;
	}
	public void setText(String stext) {
		this.text = stext;
		cursor = text.length();
	}
}
